package sse

import (
	"fmt"
	"io"

	"github.com/labstack/echo/v4"
)

// SetSSEHeaders 设置SSE响应头
func SetSSEHeaders(c echo.Context) {
	c.Response().Header().Set(echo.HeaderContentType, "text/event-stream")
	c.Response().Header().Set(echo.HeaderCacheControl, "no-cache")
	c.Response().Header().Set(echo.HeaderConnection, "keep-alive")
	c.Response().Header().Set("Access-Control-Allow-Origin", "*")
	c.Response().Header().Set("Access-Control-Allow-Headers", "Cache-Control")
}

// SendSSE 发送SSE事件
func SendSSE(w io.Writer, event *StreamEvent) error {
	if event == nil {
		return nil // 事件被过滤，不发送
	}

	sseData, err := event.ToSSEData()
	if err != nil {
		return fmt.Errorf("failed to convert event to SSE data: %w", err)
	}

	if _, err := fmt.Fprint(w, sseData); err != nil {
		return fmt.Errorf("failed to write SSE data: %w", err)
	}

	// 刷新响应缓冲区
	if flusher, ok := w.(interface{ Flush() }); ok {
		flusher.Flush()
	}

	return nil
}

// SendSSEMessage 发送简单的SSE消息（用于调试或特殊情况）
func SendSSEMessage(w io.Writer, eventType, data string) error {
	sseData := fmt.Sprintf("event: %s\ndata: %s\n\n", eventType, data)

	if _, err := fmt.Fprint(w, sseData); err != nil {
		return fmt.Errorf("failed to write SSE message: %w", err)
	}

	// 刷新响应缓冲区
	if flusher, ok := w.(interface{ Flush() }); ok {
		flusher.Flush()
	}

	return nil
}

// SendSSEError 发送错误事件
func SendSSEError(w io.Writer, conversationID interface{}, code, message, details string) error {
	var convID string
	if conversationID != nil {
		convID = fmt.Sprintf("%v", conversationID)
	}

	errorData := fmt.Sprintf(`{"conversation_id":"%s","error":{"code":"%s","message":"%s","details":"%s"}}`,
		convID, code, message, details)

	return SendSSEMessage(w, "error", errorData)
}

// SendSSEEnd 发送SSE流结束信号
func SendSSEEnd(w io.Writer) error {
	// 发送标准的SSE结束事件
	if _, err := fmt.Fprint(w, "event: close\ndata: [DONE]\n\n"); err != nil {
		return fmt.Errorf("failed to send SSE end signal: %w", err)
	}

	// 刷新响应缓冲区
	if flusher, ok := w.(interface{ Flush() }); ok {
		flusher.Flush()
	}

	return nil
}
